<?php

namespace SDK;

use Exception;

function generate_signature($params, $app_secret) {
    $filtered_params = array_filter($params, function($key) {
        return $key !== "sign";
    }, ARRAY_FILTER_USE_KEY);
    ksort($filtered_params);
    $str_to_sign = http_build_query($filtered_params, '', '&', PHP_QUERY_RFC3986);
    $signature = hash_hmac('sha256', $str_to_sign, $app_secret,false);
    return $signature;
}

function extract_params($method, $query_params, $body_params) {
    $params = array_filter($query_params, function($value) {
        return  trim($value) !== '';
    });

    if (in_array($method, ["POST", "PUT", "PATCH","DELETE"])) {
        if (is_array($body_params)) {
            foreach ($body_params as $key => $value) {
                if (is_array($value)) {
                    $params[$key] = implode(',', array_map('strval', $value));
                } else {
                    $params[$key] = strval($value);
                }
            }
        } else {
            throw new Exception("Unsupported request body format");
        }
    }
    return $params;
}

class BuildClient {
    private $app_id;
    private $app_secret;

    public function __construct($app_id, $app_secret) {
        $this->app_id = $app_id;
        $this->app_secret = $app_secret;
    }

    public function build_get_param($params) {
        $timestamp = strval(value: time());
        $params['app_id'] = $this->app_id;
        $params['timestamp'] = $timestamp;
        $params['sign'] = generate_signature(extract_params("GET", $params, $params), $this->app_secret);
        return $params;
    }

    public function build_post_param($params) {
        $timestamp = strval(value: time());
        $params['app_id'] = $this->app_id;
        $params['timestamp'] = $timestamp;
        $params['sign'] = generate_signature(extract_params("POST", [], $params), $this->app_secret);
        return $params;
    }
}

?>